package com.kuangstudy.controller;

import com.kuangstudy.constant.RedisConstants;
import com.kuangstudy.entity.Product;
import com.kuangstudy.service.hotproduct.HotProductListService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author panghu
 * @version 1.0.0
 * @createTime 2023年09月19日 20:58:00
 * @Description
 */
@RestController
@Api(tags = "淘宝展示热点商品")
public class HotProductListController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HotProductListService hotProductListService;

    @PostMapping("/select/hot/products")
    @ApiOperation("生成热点数据")
    public List<Product> selectHotProducts(@RequestParam(defaultValue = "1") Integer pageNo, @RequestParam(defaultValue = "8") Integer pageSize) {
        if (pageNo <= 0) {
            pageNo = 0;
        }
        // 1: 计算分页的起始页
        int start = (pageNo - 1) * pageSize;
        // 2: 计算分页的结束页
        int end = start + pageSize - 1;
        try {
            // 3: 查询列表中对应的产品信息进行返回
            List<Product> productList = this.redisTemplate.opsForList().range(RedisConstants.HOT_PRODUCT_LIST_MASTER, start, end);
            // 4: 如果查询不到就去数据库查询
            if (CollectionUtils.isEmpty(productList)) {
                // todo: 查询数据库，存在缓存击穿的情况，大量的并发请求进来，可能把数据库冲垮
                // productList = hotProductListService.loadHotProductInfo();
                productList = this.redisTemplate.opsForList().range(RedisConstants.HOT_PRODUCT_LIST_SLAVE,start,end);
            }
            return productList;
        } catch (Exception ex) {
            throw new RuntimeException("服务器忙碌中!!!");
        }
    }

}
